#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

long long leftcount(int len, int pos, vector<int>& num)
{
    long long res = 0;
    int rightmin = len;
    pos--;
    while (pos >= 0)
    {
        if (num[pos] >= rightmin)
            res += rightmin;
        else
        {
            res += num[pos];
            rightmin = num[pos];
        }
        pos--;
    }
    return res;
}

long long rightcount(int len, int pos, vector<int>& num)
{
    int n = num.size();
    long long res = 0;
    int leftmin = len;
    pos++;
    while (pos < n)
    {
        if (num[pos] >= leftmin)
            res += leftmin;
        else
        {
            res += num[pos];
            leftmin = num[pos];
        }
        pos++;
    }
    return res;
}

long long maximumSumOfHeights(vector<int>& maxHeights) {
    priority_queue<pair<int, int>> pq;
    for (int i = 0; i < maxHeights.size(); i++)
    {
        pq.push(make_pair(maxHeights[i], i));
    }

    long long nmax = 0;
    while (!pq.empty())
    {
        int length = pq.top().first, pos = pq.top().second;
        pq.pop();
        long long count = length + leftcount(length, pos, maxHeights) + rightcount(length, pos, maxHeights);
        if (count > nmax)
            nmax = count;
    }
    return nmax;
}

long long _maximumSumOfHeights(vector<int>& maxHeights) {
    long long nmax = 0;
    for (int i = 0; i < maxHeights.size(); i++)
    {
        long long count = maxHeights[0] + leftcount(maxHeights[0], i, maxHeights) + rightcount(maxHeights[0], i, maxHeights);
        if (count > nmax)
            nmax = count;
    }
    return nmax;
}

int main()
{
    vector<int> v = { 5,3,4,1,1 };
    cout << _maximumSumOfHeights(v) << endl;
    return 0;
}